﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.Entities;
using ARR.UI.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;
using ARR.UI.Commands;
using System.Collections;
using Telerik.Windows.Controls.GridView;
using DDF.Entity;
using ARR.UI.Helpers;
using System.Windows;
using ARR.Shared;

namespace ARR.UI.ViewModels
{
    class BenchmarkEditViewModel : ViewModelBase
    {
        private IRangeReviewModel model;
        private bool isEditSession;
        private ICommand storesGV_SelectionChangedCommand;
        private ICommand saveCommand;
        private ICommand cancelCommand;
        private bool isStoresOption;
        private bool isHistoryOption;
        private ICommand rowLoaded;
        private Entities.RangeReview selectedRangeReview;
        private ICommand historiesGV_SelectionChangedCommand;
        private ICommand historyGV_RowLoadedCommand;

        public BenchmarkEditViewModel(IRangeReviewModel model, RangeReview rangeReview, RangeReviewBenchmark benchmark)
        {
            if (model == null)
                throw new ArgumentNullException("model");
            if (rangeReview == null)
                throw new ArgumentNullException("rangeReview");

            this.model = model;
            this.RangeReview = rangeReview;

            if (benchmark != null)
            {
                this.isEditSession = true;
                CurrentBenchmark = benchmark;

                if (CurrentBenchmark.HistoryGroup != null)
                {
                    IsHistoryOption = true;

                    if (CurrentBenchmark.HistoryGroup != null && CurrentBenchmark.HistoryGroup.Members != null && CurrentBenchmark.HistoryGroup.Members.Any())
                    {
                        foreach(var history in model.AllHistories)
                        {
                            HistoryGroupMember member = CurrentBenchmark.HistoryGroup.Members.SingleOrDefault(x => x.HistoryId == history.Id);

                            if (member != null)
                            {
                                history.TargetRate = member.TargetRate;
                                history.TargetSpacesConvertion = member.TargetSpacesConversion;
                                history.TargetFuelConvertion = member.TargetFuelsConversion;
                            }
                        }
                    }
                }
                else if(CurrentBenchmark.StoreGroup != null)
                {
                    IsStoresOption = true;
                }
            }
            else
            {
                this.isEditSession = false;
                CurrentBenchmark = new RangeReviewBenchmark { RangeReviewSourceId = rangeReview.Id };
                CurrentBenchmark.StoreGroup = new StoreGroup { Members = new List<StoreGroupMember>() };
                CurrentBenchmark.HistoryGroup = new HistoryGroup { Members = new List<HistoryGroupMember>() };
            }



            this.DisplayName = Labels.TituloBenchmarks;
        }


        public ICommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new RelayCommand(param => SaveBenchmark());
                }
                return saveCommand;
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new RelayCommand(param => Cancel());
                }
                return cancelCommand;
            }
        }

        public ICommand StoresGV_SelectionChangedCommand
        {
            get
            {
                if (storesGV_SelectionChangedCommand == null)
                {
                    storesGV_SelectionChangedCommand = new RelayCommand(param => GetSelectedStores(param as IList));
                }
                return storesGV_SelectionChangedCommand;
            }
        }

        public ICommand HistoriesGV_SelectionChangedCommand
        {
            get
            {
                if (historiesGV_SelectionChangedCommand == null)
                {
                    historiesGV_SelectionChangedCommand = new RelayCommand(param => GetSelectedHistories(param as IList));
                }
                return historiesGV_SelectionChangedCommand;
            }
        }

        public ICommand RowLoaded
        {
            get
            {
                if (rowLoaded == null)
                {
                    rowLoaded = new RelayCommand(e => OnStoresGVRowLoaded(e as RowLoadedEventArgs));
                }
                return rowLoaded;
            }
        }

        public ICommand HistoryGV_RowLoadedCommand
        {
            get
            {
                if (historyGV_RowLoadedCommand == null)
                {
                    historyGV_RowLoadedCommand = new RelayCommand(e => OnHistoryGVRowLoaded(e as RowLoadedEventArgs));
                }
                return historyGV_RowLoadedCommand;
            }
        }
          
        public RangeReview RangeReview { get; set; }

        public RangeReview SelectedRangeReview
        {
            get { return selectedRangeReview; }
            set
            {
                selectedRangeReview = value;
                if (value != null)
                {
                    CurrentBenchmark.RangeReviewTargetId = selectedRangeReview.Id;
                    CurrentBenchmark.RangeReviewTargetTitle = selectedRangeReview.Title;
                }
            }
        }

        public RangeReviewBenchmark CurrentBenchmark { get; set; }

        public ObservableCollection<Currency> Currencies
        {
            get
            {
                return model.Currencies;
            }
        }

        public ObservableCollection<Store> Stores
        {
            get
            {
                return model.Stores;
            }
        }

        public ObservableCollection<History> AllHistories
        {
            get
            {
                return new ObservableCollection<History>(model.AllHistories);
            }
        }

        public List<Store> SelectedStores { get; set; }

        public List<History> SelectedHistories { get; set; }

        public ObservableCollection<RangeReview> RangeReviews
        {
            get
            {
                return new ObservableCollection<RangeReview>(model.RangeReviews.Where(x => x.Id != CurrentBenchmark.RangeReviewSourceId));
            }
        }

        public bool IsStoresOption
        {
            get { return isStoresOption; }
            set
            {
                isStoresOption = value;
                OnPropertyChanged<BenchmarkEditViewModel>(p => p.IsStoresOption);
                OnPropertyChanged<BenchmarkEditViewModel>(p => p.IsVisibleStores);
            }
        }

        public bool IsHistoryOption
        {
            get { return isHistoryOption; }
            set
            {
                isHistoryOption = value;
                OnPropertyChanged<BenchmarkEditViewModel>(p => p.IsHistoryOption);
                OnPropertyChanged<BenchmarkEditViewModel>(p => p.IsVisibleHistory);
            }
        }
                
        public Visibility IsVisibleStores
        {
            get
            {
                return IsStoresOption ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        public Visibility IsVisibleHistory
        {
            get
            {
                return isHistoryOption ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        public void TriggerAllHistoriesPropertyChanged()
        {
            var temp = model.AllHistories;
            model.AllHistories = new List<History>();

            OnPropertyChanged<BenchmarkEditViewModel>(p => p.AllHistories);

            model.AllHistories = temp;
            OnPropertyChanged<BenchmarkEditViewModel>(p => p.AllHistories);
        }


        private void SaveBenchmark()
        {
            if (CurrentBenchmark.IsValid)
            {
                if (IsHistoryOption)
                {
                    CurrentBenchmark.StoreGroup = null;
                    CurrentBenchmark.StoreGroupId = null;
                    CurrentBenchmark.RangeReviewTargetId = null;
                    CurrentBenchmark.RangeReviewTargetTitle = null;

                    SetHistoryGroup();
                }
                else if (IsStoresOption)
                {
                    CurrentBenchmark.RangeReviewTargetId = null;
                    CurrentBenchmark.RangeReviewTargetTitle = null;
                    CurrentBenchmark.HistoryGroup = null;
                    CurrentBenchmark.HistoryGroupId = null;

                    SetStoresGroup();
                }

                if (!isEditSession)
                    RangeReview.Benchmarks.Add(CurrentBenchmark);

                WindowManager.CloseView(this, true);
            }
        }

        private void SetStoresGroup()
        {
            if (SelectedStores != null && SelectedStores.Any())
            {
                CurrentBenchmark.StoreGroup.Members.Clear();

                SelectedStores.ForEach(st =>
                    {
                        CurrentBenchmark.StoreGroup.Members.Add(new StoreGroupMember
                            {
                                StoreId = st.Id,
                                Store = st,
                                StoreGroupId = CurrentBenchmark.StoreGroup.Id
                            });
                    });
            }
        }

        private void SetHistoryGroup()
        {
            if (SelectedHistories != null && SelectedHistories.Any())
            {
                CurrentBenchmark.HistoryGroup.Members.Clear();

                SelectedHistories.ForEach(x =>
                {
                    CurrentBenchmark.HistoryGroup.Members.Add(new HistoryGroupMember
                    {
                        HistoryId = x.Id,
                        History = x,
                        HistoryGroupId = CurrentBenchmark.HistoryGroup.Id,
                        TargetFuelsConversion = x.TargetFuelConvertion,
                        TargetSpacesConversion = x.TargetSpacesConvertion,
                        TargetRate = x.TargetRate
                    });
                });
            }
        }

        private void Cancel()
        {
            WindowManager.CloseView(this, false);
        }

        private void GetSelectedStores(IList selectedItems)
        {
            IEnumerable<Store> stores = (selectedItems.Cast<Store>());
            SelectedStores = stores.ToList();
        }

        private void GetSelectedHistories(IList selectedItems)
        {
            IEnumerable<History> histories = (selectedItems.Cast<History>());
            SelectedHistories = histories.ToList();
        }

        public void OnStoresGVRowLoaded(RowLoadedEventArgs e)
        {
            if (CurrentBenchmark.StoreGroup != null && CurrentBenchmark.StoreGroup.Members != null && CurrentBenchmark.StoreGroup.Members.Any())
            {
                if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                {
                    Store store = e.DataElement as Store;

                    if (CurrentBenchmark.StoreGroup.Members.Select(st => st.Store.Id).Contains(store.Id))
                        e.Row.IsSelected = true;
                }
            }
        }

        public void OnHistoryGVRowLoaded(RowLoadedEventArgs e)
        {
            if (CurrentBenchmark.HistoryGroup != null && CurrentBenchmark.HistoryGroup.Members != null && CurrentBenchmark.HistoryGroup.Members.Any())
            {
                if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                {
                    History history = e.DataElement as History;

                    HistoryGroupMember member = CurrentBenchmark.HistoryGroup.Members.SingleOrDefault(x => x.HistoryId == history.Id);
                    
                    if(member != null)
                    {
                        e.Row.IsSelected = true;
                    }
                }
            }
        }
        
    }
}
